package cn.edu.lcu.cs.ssm.util;

import java.io.IOException;
import java.io.Reader;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

/**
 * MyBatis的工具类，用于获取Session。若与Spring集成，则不需要此类。
 * 
 * @author Ling
 *
 */
public class MyBatisUtil {
	protected static SqlSessionFactory factory;

	// 静态初始化块，用来初始化factory。此代码仅执行一次。
	static {
		try {
			Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
			SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
			factory = builder.build(reader);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static SqlSession getSession() {
		return factory.openSession();
	}
}
